﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using LY.Entity;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Entity.Jsons;
using LY.Interface;

namespace QJ.CMS.Areas.Admin.Controllers
{
    public class MenuController : Controller
    {
        //
        // GET: /Menu/
        private static IMenuService _aservice;
        public MenuController(IMenuService aService)
        {
            _aservice = aService;
        }

        public ActionResult Index()
        {
            return View();
        }

        #region 栏目
        /// <summary>
        /// 栏目列表界面
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuList()
        {
            return View();
        }

        /// <summary>
        /// 栏目树界面
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuTree()
        {
            return View();
        }

        /// <summary>
        /// 栏目列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult MenuList(int? Id, ArticleSearch search, FormCollection form)
        {
            JsonQTable at = null;
            if (Id.HasValue)
            {
                PageView view = new PageView(form);
                string colkey = form["colkey"];
                string colsinfo = form["colsinfo"];
                PagedList<C_Menu> menulist = _aservice.QueryMenuListId(Id, search, view);

                at = JsonQTable.ConvertFromPagedList<C_Menu>(menulist, colkey, colsinfo.Split(','));
                return Json(at);
            }
            else
            {
                PageView view = new PageView(form);
                string colkey = form["colkey"];
                string colsinfo = form["colsinfo"];
                PagedList<C_Menu> menulist = _aservice.QueryMenuList(search, view);

                at = JsonQTable.ConvertFromPagedList<C_Menu>(menulist, colkey, colsinfo.Split(','));
                return Json(at);
            }
        }

        /// <summary>
        /// 栏目新增或编辑操作，返回不同状态界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult MenuEdit(int? id)
        {
            C_Menu menu = null;
            if (id.HasValue)
            {
                menu = _aservice.GetMenu(id.Value);

                string SubMenuId = "";
                List<C_Menu> list = _aservice.GetMenuSub(id.Value);
                foreach (var item in list)
                {
                    SubMenuId += item.ID.ToString() + ",";
                }
                if (SubMenuId != "")
                {
                    SubMenuId = SubMenuId.Substring(0, SubMenuId.Length - 1);
                }
                ViewBag.SubMenuId = SubMenuId;

                if (menu.Sequence == null)
                {
                    menu.Sequence = 0;
                }
            }
            else
            {
                menu = new C_Menu();
                menu.Sequence = 0;
            }
            return View(menu);
        }

        /// <summary>
        /// 新增或编辑栏目信息保存操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult MenuSave(int? id, int? UpperID, string NameE, string UpperName, C_Menu menu, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                string errmsg = "";
                //输入验证
                if (!Validate(id, UpperID, NameE, UpperName, menu, out errmsg))
                {
                    rMsg.Status = -1;
                    rMsg.Message = errmsg;
                }
                else
                {
                    int ret = _aservice.SaveMenu(menu);
                    if (ret > 0)
                    {
                        rMsg.Status = 1;
                        rMsg.Message = "操作成功！";
                    }
                    else
                    {
                        rMsg.Status = -1;
                        rMsg.Message = "意外错误，请稍后重试！";
                    }
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        /// <summary>
        /// 输入栏目信息验证
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        private static bool Validate(int? id, int? UpperID, string NameE, string UpperName, C_Menu menu, out string errmsg)
        {
            errmsg = "";
            if (menu.Name == "" || menu.Name == null)
            {
                errmsg = "请输入栏目名称！";
                return false;
            }
            if (menu.Code == "" || menu.Code == null)
            {
                errmsg = "请输入栏目Code！";
                return false;
            }
            if (UpperID != null || UpperName != "")
            {
                menu.UpperID = UpperID;
                menu.UpperName = UpperName;
            }
            else
            {
                errmsg = "请选择栏目隶属！";
                return false;
            }
            if (id == 0)
            {
                int code = _aservice.GetCodeNum(menu.Code);
                if (code > 0)
                {
                    errmsg = "抱歉,当前栏目Code已经存在,请重新输入！";
                    return false;
                }
            }
            else
            {
                int code2 = _aservice.GetCodeNum(menu.ID, menu.Code);
                if (code2 > 0)
                {
                    errmsg = "抱歉,当前栏目Code已经存在,请重新输入！";
                    return false;
                }
            }
            if (!menu.Sequence.HasValue)
            {
                menu.Sequence = 0;
            }
            if (NameE == null || NameE == "")
            {
                menu.NameE = menu.Name;
            }
            if (menu == null)
            {
                errmsg = "参数错误！";
                return false;
            }
            return true;
        }

        /// <summary>
        /// 栏目删除操作
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MenuDelete(int id, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                }
                int checkarticle = _aservice.CheckArticle(id);
                if (checkarticle > 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "请先删除栏目下的文章信息！";
                    return Json(rMsg);
                }
                int ret = _aservice.DeleteMenu(id);
                if (ret <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "请先删除当前栏目的子栏目！";
                }
                else
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        [HttpPost]
        public string GetTopMenu()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[{ id: 0, pId: 0, name: '根节点', open:true},");
            //string menu = "[{ id: 1, pId: 0, name: '功能菜单', open:true,children: [{ }] }]";
            List<C_Menu> list2 = _aservice.GetUpperMenuList(0);
            string isParent2 = string.Empty;
            if (list2.Count > 0)
            {
                //sb.Append("[");
                for (int i = 0; i < list2.Count; i++)
                {
                    sb.Append("{id:" + list2[i].ID);
                    sb.Append(",pId:" + list2[i].UpperID + "");
                    sb.Append(",name:'" + list2[i].Name + "'");
                    List<C_Menu> chlist = _aservice.GetUpperMenuList(list2[i].ID);
                    if (chlist.Count > 0)
                    {
                        isParent2 = "true";
                    }
                    else
                    {
                        isParent2 = "false";
                    }
                    sb.Append(",isParent:" + isParent2 + "},");
                }
            }
            return sb.ToString().TrimEnd(',') + "]";
        }

        [HttpPost]
        public JsonResult GetData(int? id)
        {
            List<Node> nodeList = new List<Node>();
            if (id.HasValue)
            {
                //DataView dv = _mservice.GetMenuView(id.Value);
                List<C_Menu> list = _aservice.GetUpperMenuList(id.Value);
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        Node node = new Node();
                        node.id = Convert.ToInt32(list[i].ID);
                        node.pId = Convert.ToInt32(list[i].UpperID);
                        node.name = list[i].Name;
                        List<C_Menu> chlist = _aservice.GetUpperMenuList(node.id);
                        if (chlist.Count > 0)
                        {
                            node.isParent = true;
                        }
                        else
                        {
                            node.isParent = false;
                        }
                        nodeList.Add(node);
                    }
                }
            }
            return Json(nodeList);
        }

        class Node
        {
            /// <summary>
            /// 节点编号
            /// </summary>
            public int id
            {
                get;
                set;
            }

            /// <summary>
            /// 父节点编号
            /// </summary>
            public int pId
            {
                get;
                set;
            }

            /// <summary>
            /// 节点名称
            /// </summary>
            public string name
            {
                get;
                set;
            }

            /// <summary>
            /// 是否为父节点
            /// </summary>
            public bool isParent
            {
                get;
                set;
            }
            ///这里可以继续扩展节点的其他属性
        }
        #endregion
    }
}
